package cn.acheng1314.im.common.handler;

import cn.acheng1314.im.common.server.AbstractServer;
import cn.acheng1314.im.common.server.ServerContext;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@ChannelHandler.Sharable
public abstract class ServerAbstractHeartbeatHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(ServerAbstractHeartbeatHandler.class);

    public ServerAbstractHeartbeatHandler() {
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            if (e.state() == IdleState.WRITER_IDLE) {
                logger.debug("长时间未写入消息=>写入心跳");
                writeHeartbeat(ctx);
            } else if (e.state() == IdleState.READER_IDLE) {
                logger.debug("长时间未读取消息=>关闭链接");
                ctx.channel().close();
            }
        }
        super.userEventTriggered(ctx, evt);
    }

    /**
     * 写入心跳数据
     *
     * @param ctx
     */
    protected abstract void writeHeartbeat(ChannelHandlerContext ctx);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (isHeartbeat(ctx, msg)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Heartbeat received.");
            }

            AbstractServer server = ServerContext.getContext().getServer();
            if (server != null) {
                server.getCountInfo().getHeartbeatNum().incrementAndGet();
            }
            return;
        }
        super.channelRead(ctx, msg);
    }

    /**
     * 检查是否为心跳消息
     *
     * @param ctx
     * @param msg
     * @return
     */
    protected abstract boolean isHeartbeat(ChannelHandlerContext ctx, Object msg);


}
